﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using DBEntity;
using iver.Entity;


//200: '服务器成功返回请求的数据。',
//  201: '新建或修改数据成功。',
//  202: '一个请求已经进入后台排队（异步任务）。',
//  204: '删除数据成功。',
//  400: '发出的请求有错误，服务器没有进行新建或修改数据的操作。',
//  401: '用户没有权限（令牌、用户名、密码错误）。',
//  403: '用户得到授权，但是访问是被禁止的。',
//  404: '发出的请求针对的是不存在的记录，服务器没有进行操作。',
//  406: '请求的格式不可得。',
//  410: '请求的资源被永久删除，且不会再得到的。',
//  422: '当创建一个对象时，发生一个验证错误。',
//  500: '服务器发生错误，请检查服务器。',
//  502: '网关错误。',
//  503: '服务不可用，服务器暂时过载或维护。',
//  504: '网关超时。',
namespace iver.Controllers
{

    public class UserController : ApiController
    {
        /// <summary>
        /// 获取角色列表，用于用户管理
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [HttpPost]
        public ResResult BaseRoleList([FromBody]ReqList req)
        {
            AuthInfo authInfo;
            if (!ReqBase.isAuth(out authInfo))
            {
                return new ResResult
                {
                    success = false,
                    rescode = ResCode.FailAuth,
                };
            }
            iverDB db = new iverDB();
            var roleList = from u in db.sysRole
                           where authInfo.isSuperAdmin ? u.isEnable == true : u.isEnable == true && u.createBy == authInfo.userId
                           orderby u.id descending
                           select u;
            var arr = roleList.Skip(req.limit * (req.page - 1)).Take(req.limit);
            int count = roleList.Count();
            return new ResResult
            {
                success = true,
                result = new
                {
                    count,
                    arr,
                },
            };
        }
        /// <summary>
        /// 列表
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [HttpPost]
        public ResResult UserList([FromBody]ReqList req)
        {
            AuthInfo authInfo;
            if (!ReqBase.isAuth(out authInfo))
            {
                return new ResResult
                {
                    success = false,
                    rescode = ResCode.FailAuth,
                };
            }
            iverDB db = new iverDB();
            var list = (from u in db.sysUser
                        join fu in db.sysUser on u.fid equals fu.id into temp1
                        from fuser in temp1.DefaultIfEmpty()
                        where authInfo.isSuperAdmin ? 1 == 1 : u.fid == authInfo.userId
                        orderby u.id descending
                        select new
                        {
                            u.id,
                            u.createTime,
                            u.fid,
                            u.isEnable,
                            u.pwd,
                            u.remark,
                            u.trueName,
                            u.userName,
                            u.userType,
                            u.authority,
                            u.roles,
                            fuserName = fuser.userName,
                            ftrueName = fuser.trueName,
                        });
            var arr = list.Skip(req.limit * (req.page - 1)).Take(req.limit);
            int count = list.Count();
            return new ResResult
            {
                success = true,
                result = new
                {
                    count,
                    arr,
                }
            };
        }
        /// <summary>
        /// 列表
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [HttpPost]
        public ResResult UserRoleList([FromBody]ReqListQuery req)
        {
            AuthInfo authInfo;
            if (!ReqBase.isAuth(out authInfo))
            {
                return new ResResult
                {
                    success = false,
                    rescode = ResCode.FailAuth,
                };
            }
            iverDB db = new iverDB();

            var list = (from u in db.sysUserRole
                        where req.id == u.userId
                        orderby u.id descending
                        select u);
            var arr = list.Skip(req.limit * (req.page - 1)).Take(req.limit);
            int count = list.Count();

            return new ResResult
            {
                success = true,
                result = new
                {
                    count,
                    arr,
                },
            };
        }
        /// <summary>
        /// 添加用户
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [HttpPost]
        public ResResult UserAdd([FromBody]sysUser req)
        {
            AuthInfo authInfo;
            if (!ReqBase.isAuth(out authInfo))
            {
                return new ResResult
                {
                    success = false,
                    rescode = ResCode.FailAuth,
                };
            }
            iverDB db = new iverDB();
            sysUser sysuser = db.sysUser.FirstOrDefault(p => p.userName == req.userName);
            if (sysuser != null)
            {
                return new ResResult()
                {
                    success = false,
                    rescode = ResCode.FailParams,
                    result = "用户已存在",
                };
            }

            DateTime now = DateTime.Now;
            req.fid = authInfo.userId;
            req.createTime = now;
            db.sysUser.Add(req);
            db.SaveChanges();
            return new ResResult
            {
                success = true,
                rescode = ResCode.SuccessAdd,
                result = new
                {
                    id = req.id,
                },
            };
        }
        /// <summary>
        /// 
        /// </summary>
        public class UserRole : sysUser
        {
            /// <summary>
            /// 
            /// </summary>
            public List<int> roleIdList;
        }
        /// <summary>
        /// 添加用户角色
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [HttpPost]
        public ResResult UserRoleAdd([FromBody]UserRole req)
        {
            AuthInfo authInfo;
            if (!ReqBase.isAuth(out authInfo))
            {
                return new ResResult
                {
                    success = false,
                    rescode = ResCode.FailAuth,
                };
            }
            iverDB db = new iverDB();

            List<sysUserRole> UserRoleList = new List<sysUserRole>();
            for (int i = 0; i < req.roleIdList.Count; i++)
            {
                UserRoleList.Add(new sysUserRole()
                {
                    roleId = req.roleIdList[i],
                    userId = req.id,
                });
            }
            db.sysUserRole.AddRange(UserRoleList);
            int addUserRoleCount = db.SaveChanges();

            return new ResResult
            {
                success = true,
                rescode = ResCode.SuccessAdd,
                result = new
                {
                    addUserRoleCount
                },
            };
        }
        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [HttpPost]
        public ResResult UserEdit([FromBody]sysUser req)
        {
            AuthInfo authInfo;
            if (!ReqBase.isAuth(out authInfo))
            {
                return new ResResult
                {
                    success = false,
                    rescode = ResCode.FailAuth,
                };
            }
            iverDB db = new iverDB();
            sysUser model = db.sysUser.FirstOrDefault(u => u.id == req.id);
            if (model == null)
            {
                return new ResResult
                {
                    success = false,
                    rescode = ResCode.FailParams,
                };
            }

            model.userName = req.userName == null ? model.userName : req.userName;
            model.trueName = req.trueName == null ? model.trueName : req.trueName;
            model.pwd = req.pwd == null ? model.pwd : req.pwd;
            model.userType = req.userType == null ? model.userType : req.userType;
            model.isEnable = req.isEnable == null ? model.isEnable : req.isEnable;
            model.remark = req.remark == null ? model.remark : req.remark;
            model.fid = req.fid == null ? model.fid : req.fid;
            model.roles = req.roles == null ? model.roles : req.roles;
            model.authority = req.authority == null ? model.authority : req.authority;
            int result = db.SaveChanges();
            return new ResResult
            {
                success = true,
                rescode = ResCode.SuccessEdit,
                result = new
                {
                    changeCount = result,
                },
            };
        }
        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [HttpPost]
        public ResResult UserEditWithRole([FromBody]UserRole req)
        {
            AuthInfo authInfo;
            if (!ReqBase.isAuth(out authInfo))
            {
                return new ResResult
                {
                    success = false,
                    rescode = ResCode.FailAuth,
                };
            }

            iverDB db = new iverDB();
            sysUser model = db.sysUser.FirstOrDefault(u => u.id == req.id);
            if (model == null)
            {
                return new ResResult
                {
                    success = false,
                    rescode = ResCode.FailParams,
                };
            }
            //除本用户名外是否于其他用户名冲突
            if(model.userName != req.userName)
            {
                int queryCount = db.sysUser.Count(p => p.userName == req.userName);
                if (queryCount > 0)
                {
                    return new ResResult()
                    {
                        success = false,
                        rescode = ResCode.FailParams,
                        result = "用户已存在",
                    };
                }
            }
            
           //开启事务
           var tran = db.Database.BeginTransaction();
            try
            {
                //删除关系表
                int userId = model.id;
                var listUserRole = db.sysUserRole.Where(u => u.userId == userId);
                db.sysUserRole.RemoveRange(listUserRole);

                //添加关系表
                List<sysUserRole> UserRoleList = new List<sysUserRole>();
                for (int i = 0; i < req.roleIdList.Count; i++)
                {
                    UserRoleList.Add(new sysUserRole()
                    {
                        userId = userId,
                        roleId = req.roleIdList[i],
                    });
                }
                db.sysUserRole.AddRange(UserRoleList);

                model.userName = req.userName == null ? model.userName : req.userName;
                model.trueName = req.trueName == null ? model.trueName : req.trueName;
                model.pwd = req.pwd == null ? model.pwd : req.pwd;
                model.userType = req.userType == null ? model.userType : req.userType;
                model.isEnable = req.isEnable == null ? model.isEnable : req.isEnable;
                model.remark = req.remark == null ? model.remark : req.remark;
                model.fid = req.fid == null ? model.fid : req.fid;
                model.roles = req.roles == null ? model.roles : req.roles;
                model.authority = req.authority == null ? model.authority : req.authority;
                int changeCount = db.SaveChanges();
                //提交事务
                tran.Commit();
                return new ResResult
                {
                    success = true,
                    rescode = ResCode.SuccessEdit,
                    result = new
                    {
                        delUserRoleCount = listUserRole.Count(),
                        addUserRoleCount = UserRoleList.Count(),
                        changeCount,
                    },
                };
            }
            catch (Exception ex)
            {
                tran.Rollback();
                return new ResResult
                {
                    success = false,
                    rescode = ResCode.FailCatch,
                    result = ex.Message,
                };
            }



        }
        /// <summary>
        /// 删除用户和用户角色
        /// </summary>
        /// <param name="req">id数组</param>
        /// <returns></returns>
        [HttpPost]
        public ResResult UserDel([FromBody]ReqID<List<int>> req)
        {
            AuthInfo authInfo;
            if (!ReqBase.isAuth(out authInfo))
            {
                return new ResResult
                {
                    success = false,
                    rescode = ResCode.FailAuth,
                };
            }
            iverDB db = new iverDB();
            sysUser model = db.sysUser.FirstOrDefault(u => u.fid == -1);
            if (req.id.Contains(model.id))
            {
                return new ResResult
                {
                    success = false,
                    rescode = ResCode.FailParams,
                    result = "不能删除超级管理员",
                };
            }
            var listUser = db.sysUser.Where(u => req.id.Contains(u.id));
            int delUserCount = listUser.Count();
            if (delUserCount == 0)
            {
                return new ResResult
                {
                    success = false,
                    rescode = ResCode.FailParams,
                };
            }
            //开启事务
            var tran = db.Database.BeginTransaction();
            try
            {
                int delUserRoleCount = 0;
                //删除关系表
                for (int i = 0; i < delUserCount; i++)
                {
                    int userId = listUser.ToList()[i].id;
                    var listUserRole = db.sysUserRole.Where(u => u.userId == userId);
                    db.sysUserRole.RemoveRange(listUserRole);
                    delUserRoleCount += listUserRole.Count();
                }
                int changeCount = db.SaveChanges();

                //删除主表
                db.sysUser.RemoveRange(listUser);
                db.SaveChanges();
                //提交事务
                tran.Commit();
                return new ResResult
                {
                    success = true,
                    rescode = ResCode.SuccessDel,
                    result = new
                    {
                        delUserCount,
                        delUserRoleCount,
                        changeCount,
                    },
                };
            }
            catch (Exception ex)
            {
                tran.Rollback();
                return new ResResult
                {
                    success = false,
                    rescode = ResCode.FailCatch,
                    result = ex.Message,
                };
            }


        }
    }
}